package com.qfedu.edu.seckill.orderservice.interceptor;

import com.qfedu.edu.seckill.exception.BusinessException;
import com.qfedu.edu.seckill.orderservice.slot.base.SlotChain;
import com.qfedu.edu.seckill.result.R;
import com.qfedu.edu.seckill.result.ResponseCode;
import com.qfedu.edu.seckill.utils.HttpResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobobo
 * @title: GlobalInterceptor
 * @projectName cd-java-2404-seckill-parent
 * @description: TODO
 * @date 2025/2/6  9:35
 */
@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

    @Autowired
    private SlotChain slotChain;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            slotChain.dealRequest(request,response);
            return true;
        }catch (Exception err){
            //如果其中执行到这里来肯定就有问题
            if(err instanceof BusinessException){
                //说明是我们自己抛出的异常
                BusinessException businessException= (BusinessException) err;
                //接下来返回数据给前端
                HttpResponseUtils.sendResponse(response, R.error(businessException.getCode(),businessException.getMsg()));
            }else {
                //那就是出现了其他类型的异常
                err.printStackTrace();
                log.error("拦截器中出现了系统异常");
            }
            return false;

        }
    }
}
